package data

import (
	"sort"
	"time"
)

func Sort(timePairs ...TimePairs) []*TimePair {
	result := TimePairs{}
	for _, pair := range timePairs {
		for _, timePair := range pair {
			result = append(result, timePair)
		}
	}

	sort.Sort(result)

	return result
}

func GetDuration(timePairs []*TimePair) int64 {
	var result int64 = 0
	if len(timePairs) == 0 {
		return result
	}
	index := 1
	for i := 0; i < len(timePairs); i++ {
		if index == len(timePairs) {
			result += (timePairs[i].End.UnixNano() - timePairs[i].Start.UnixNano()) / 1e6
			break
		}
		if timePairs[i].End.Unix() < timePairs[index].Start.Unix() {
			result += (timePairs[i].End.UnixNano() - timePairs[i].Start.UnixNano()) / 1e6
		} else {
			if timePairs[i].End.Unix() < timePairs[index].End.Unix() {
				timePairs[index].Start = timePairs[i].Start
			} else {
				timePairs[index] = timePairs[i]
			}
		}
		index++
	}

	return result
}

type TimePair struct {
	Start time.Time
	End   time.Time
}

type TimePairs []*TimePair

func (s TimePairs) Len() int {
	return len(s)
}
func (s TimePairs) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s TimePairs) Less(i, j int) bool {
	return s[i].Start.Unix() < s[j].Start.Unix()
}
